package com.tomcov.client.activities;

import java.util.Comparator;
import java.util.List;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.cell.client.ActionCell;
import com.google.gwt.cell.client.ActionCell.Delegate;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.view.client.ListDataProvider;
import com.tomcov.client.ClientFactory;
import com.tomcov.client.place.MessageOutPlace;
import com.tomcov.client.place.NewMessagePlace;
import com.tomcov.client.service.MessageServiceAsync;
import com.tomcov.client.service.UserServiceAsync;
import com.tomcov.client.view.MessageOutView;
import com.tomcov.shared.Message;
import com.tomcov.shared.UserInfo;

public class MessageOutActivity extends AbstractActivity implements MessageOutView.Presenter{

	private ClientFactory clientFactory;

	/**
	 * Instantiates a new message out activity.
	 *
	 * @param clientFactory the client factory
	 */
	public MessageOutActivity(ClientFactory clientFactory){
		this.clientFactory = clientFactory;	
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		final MessageOutView messageOutView = clientFactory.getMessageOutView();
		getoutmessage();
		messageOutView.getNewButton().addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				messageOutView.getNewButton().setEnabled(false);
				goTo(new NewMessagePlace(null));
				messageOutView.getNewButton().setEnabled(true);
			}
		});
		messageOutView.setPresenter(this);
		panel.setWidget(messageOutView.asWidget());
	}

	@Override
	public void goTo(Place place) {
		clientFactory.getPlaceController().goTo(place);		
	}

	private void getoutmessage() {
		UserServiceAsync USA=clientFactory.getUSA();
		USA.getUserInSession(new AsyncCallback<UserInfo>(){
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("fail to get in session");
			}
			@Override
			public void onSuccess(final UserInfo result) {
				if(result==null){Window.alert("no user in session");}
				else{
					//System.out.println(result.getUserName());
					getMessageOut(result.getUserName(),0);
				}
			}
		});

	}

	public void getMessageOut(String Username, int nb){

		MessageServiceAsync MSA = clientFactory.getMSA();
		MSA.getMessageFrom(Username, new AsyncCallback<List<Message>>(){
			@Override
			public void onFailure(Throwable caught) {
				try{
					throw caught;
				}
				catch(NullPointerException e){

				}
				catch (Throwable e) {
					Window.alert("server fail to get message");
					e.printStackTrace();
				}
			}
			@Override
			public void onSuccess(List<Message> result) {
				if(result==null){Window.alert("server fail to get message");}
				else{ 
					//Window.alert("ca marche");
					//System.out.println(result.getFrom()+" "+result.getTo()+" "+result.getMessage());
					//List<Message> messagelist= Arrays.asList(result);

					MessageOutView messageOutView = clientFactory.getMessageOutView();
					VerticalPanel Cellcontainer=messageOutView.getCellContainer();
					Cellcontainer.clear();
					CellTable<Message> celltable = new CellTable<Message>();
					celltable.setPageSize(5);

					//from
					TextColumn<Message> FromColumn = new TextColumn<Message>() {
						@Override
						public String getValue(Message object) {
							return object.From;
						}
					};
					celltable.addColumn(FromColumn, "From");
					FromColumn.setSortable(true);
					//to
					TextColumn<Message> ToColumn = new TextColumn<Message>() {
						@Override
						public String getValue(Message object) {
							return object.To;
						}
					};
					celltable.addColumn(ToColumn, "To");
					ToColumn.setSortable(true);
					//date
					TextColumn<Message> dateColumn = new TextColumn<Message>() {
						@Override
						public String getValue(Message object) {
							return object.date.toString();
						}
					};
					celltable.addColumn(dateColumn, "Date");
					dateColumn.setSortable(true);
					
					SimplePager pager = new SimplePager();
					pager.setDisplay(celltable);
					Cellcontainer.add(pager);
					Cellcontainer.add(celltable);
					ListDataProvider<Message> dataProvider = new ListDataProvider<Message>();
					
					// Connect the table to the data provider.
					dataProvider.addDataDisplay(celltable);
					List<Message> list = dataProvider.getList();
					for (Message contact : result) {
						list.add(contact);
					}
					ListHandler<Message> FromcolumnSortHandler = new ListHandler<Message>(list);
					FromcolumnSortHandler.setComparator(FromColumn,
							new Comparator<Message>() {
						public int compare(Message o1, Message o2) {
							if (o1 == o2) {return 0;}
							if (o1 != null) {return (o2 != null) ? o1.From.compareTo(o2.From) : 1;}
							return -1;
						}
					});
					ListHandler<Message> TocolumnSortHandler = new ListHandler<Message>(list);
					TocolumnSortHandler.setComparator(ToColumn,
							new Comparator<Message>() {
						public int compare(Message o1, Message o2) {
							if (o1 == o2) {return 0;}
							if (o1 != null) {return (o2 != null) ? o1.To.compareTo(o2.To) : 1;}
							return -1;
						}
					});
					ListHandler<Message> DatecolumnSortHandler = new ListHandler<Message>(list);
					DatecolumnSortHandler.setComparator(dateColumn,
							new Comparator<Message>() {
						public int compare(Message o1, Message o2) {
							if (o1 == o2) {return 0;}
							if (o1 != null) {return (o2 != null) ? o1.date.compareTo(o2.date) : 1;}
							return -1;
						}
					});

					celltable.addColumnSortHandler(FromcolumnSortHandler);
					celltable.addColumnSortHandler(TocolumnSortHandler);
					celltable.addColumnSortHandler(DatecolumnSortHandler);

					celltable.getColumnSortList().push(dateColumn);

					celltable.addColumn( new Column<Message,String>(new ActionCell<String>( "Show Message", new Delegate<String>( )
							{
						public void execute( String text ){
							clientFactory.getMessageOutView().getMessageArea().setHTML(text);
						}
							}))
							{

						@Override
						public String getValue(Message object) {
							return object.getMessage();
						}
							} );
					
					celltable.addColumn( new Column<Message,Message>(
							new ActionCell<Message>("Delete", new Delegate<Message>(){
								public void execute(Message e ){
									
									clientFactory.getMSA().update(e,2,new AsyncCallback<Message>(){
										@Override
										public void onFailure(Throwable caught) {
											Window.alert("fail to update");
										}

										@Override
										public void onSuccess(Message result) {
											//if(result==null){Window.alert("message null");}
											//else{
												clientFactory.getMSA().delete(result, new AsyncCallback<Message>(){
													@Override
													public void onFailure(Throwable caught) {
														Window.alert("fail to deletee");
													}
													@Override
													public void onSuccess(Message result) {
														if(result!=null)Window.alert("deleted enfin");
														else 
														goTo(new MessageOutPlace(null));
													}
												});
											//}
										}

									});
								}
							}))
							{

						@Override
						public Message getValue(Message object) {
							return object;
						}
							} );


				}

			}
		});

	}



}
